package com.edmendst.xmall.service.impl;

import com.edmendst.xmall.dto.ShopInfo;
import com.edmendst.xmall.mapper.ShopMapper;
import com.edmendst.xmall.mapper.UserMapper;
import com.edmendst.xmall.pojo.Shop;
import com.edmendst.xmall.pojo.ShopExample;
import com.edmendst.xmall.pojo.User;
import com.edmendst.xmall.pojo.UserExample;
import com.edmendst.xmall.service.ShopService;
import com.edmendst.xmall.service.UserService;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Service
public class ShopServiceImpl implements ShopService {

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private UserService userService;

    @Value("${shop.logo}")
    private String LOGO_PATH;
    @Autowired
    private UserMapper userMapper;

    //    Integer  shopId;
//    @JsonProperty("shopName")
//    private String shopName;
//    @JsonProperty("shopDescription")
//    private String shopDescription;
//    private String shopLogo;
    @Override
    public int createShop(String username, String shopName) {
        Integer userIdByUserName = userService.selectUserIdByUserName(username);
        String userType = userMapper.selectByPrimaryKey(userIdByUserName).getUserType();
        if ("seller".equals(userType)|| "both".equals(userType)){
            if (userIdByUserName != null) {
                Shop shop = new Shop();
                shop.setShopName(shopName);
                shop.setUserId(userIdByUserName);
                shopMapper.insert(shop);
                return 1;
            }
            return 0;
        }
        return 0;
    }

    @Override
    public List<ShopInfo> selectShopInfoByUsername(String username) {
        Integer userIdByUserName = userService.selectUserIdByUserName(username);
        if (userIdByUserName != null) {
            ShopExample example = new ShopExample();
            example.createCriteria()
                    .andUserIdEqualTo(userIdByUserName);
            List<Shop> shops = shopMapper.selectByExampleWithBLOBs(example);
            List<ShopInfo> shopInfos = new ArrayList<>();
            for (int i = 0; i < shops.size(); i++) {
                ShopInfo shopInfo = new ShopInfo();
                shopInfo.setShopId(shops.get(i).getShopId());
                shopInfo.setShopName(shops.get(i).getShopName());
                shopInfo.setShopDescription(shops.get(i).getShopDescription());
                System.out.println(shops.get(i).getShopDescription());
                shopInfo.setShopLogo(shops.get(i).getShopLogo());
                shopInfos.add(shopInfo);
            }
            return shopInfos;
        }
        return null;
    }


    //    Integer opcode;  // 1：修改店铺名称   2：修改店铺描述
    @Override
    public int updateShopInfo(String username, ShopInfo shopInfo) {
        Integer opcode = shopInfo.getOpcode();
        Integer userIdByUserName = userService.selectUserIdByUserName(username);
       if (opcode == 1) {
            Shop shop = new Shop();
            shop.setShopName(shopInfo.getShopName());
            shop.setUserId(userIdByUserName);
            ShopExample example = new ShopExample();
            example.createCriteria()
                    .andUserIdEqualTo(userIdByUserName);
            int i = shopMapper.updateByExampleSelective(shop, example);
            return i;
        } else if (opcode == 2) {
            Shop shop = new Shop();
            shop.setShopDescription(shopInfo.getShopDescription());
            shop.setUserId(userIdByUserName);
            ShopExample example = new ShopExample();
            example.createCriteria()
                    .andUserIdEqualTo(userIdByUserName);
            int i = shopMapper.updateByExampleSelective(shop, example);
            return i;
        } else {
            return 0;
        }

    }

    @Override
    public int updateShopLogo(MultipartFile shopLogo, Integer shopId) {
        final String[] ALLOWED_EXT = {".png", ".jpg", ".jpeg", ".gif"};

        Shop shop = shopMapper.selectByPrimaryKey(shopId);
        if (shop == null) return 0;
        try {
            String fileName = shopLogo.getOriginalFilename();
            String fileExt = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
            if (!Arrays.asList(ALLOWED_EXT).contains(fileExt)) {
                throw new IllegalArgumentException("不支持的文件类型");
            }
            Path targetDir = Paths.get(LOGO_PATH, shopId.toString());
            Files.createDirectories(targetDir);

            String newFileName = UUID.randomUUID() + fileExt;
            Path targetPath = targetDir.resolve(newFileName);

            try (InputStream is = shopLogo.getInputStream()) {
                Files.copy(is, targetPath, StandardCopyOption.REPLACE_EXISTING);
            }

            String relativePath = shopId + "/" + newFileName;
            shop.setShopLogo(relativePath);
            shopMapper.updateByPrimaryKeySelective(shop);
            return 1;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }

    @Override
    @Transactional
    public Integer selectShopIdByUsername(String username) {
        Integer userIdByUserName = userService.selectUserIdByUserName(username);
        if (userIdByUserName != null) {
            ShopExample example = new ShopExample();
            example.createCriteria()
                    .andUserIdEqualTo(userIdByUserName);
            List<Shop> shops = shopMapper.selectByExample(example);
            // 空列表检查
            if (shops == null || shops.isEmpty()) {
                throw new RuntimeException("用户没有店铺");
            }

            return shops.get(0).getShopId();
        }
        return 0;
    }
}
